﻿// ipad res: 1024x748
var numOfTextObj = 0,
    numOfAudioObj = 0,
    numOfVideoObj = 0,
    numOfImageObj = 0;
var textObjects = [],
    audioObjects = [],
    videoObjects = [],
    imageObjects = [];
var selectedObjectId = null;
var textAreaFocused = false;

$(function () {
    $("#EditingCanvas").droppable({ accept: ".ObjectSetItem", drop: addNewCanvasItem });
    $("body").keyup(parseKeyPressed);
    $("#objText").button({ text: false }).draggable({
        appendTo: "#EditingCanvas", helper: "clone"
    });
    $("#objAudio").button({ text: false }).draggable({
        appendTo: "#EditingCanvas", helper: "clone"
    });
    $("#objVideo").button({ text: false }).draggable({
        appendTo: "#EditingCanvas", helper: "clone"
    });
    $("#objImage").button({ text: false }).draggable({
        appendTo: "#EditingCanvas", helper: "clone"
    });
    $("#confirmDeleteDialog").dialog({
        resizable: false,
        height: 150,
        modal: true,
        autoOpen: false,
        buttons: {
            "Delete": function () {
                $(this).dialog("close");
                removeCanvasItem();
            },
            "Cancel": function () {
                $(this).dialog("close");
            }
        }
    });

    $("#fontEditorDialog").dialog({
        resizable: false,
        height: 460,
        width: 276,
        modal: true,
        autoOpen: false,
        buttons: {
            "Save": function () {
                var val = validateFontFields();
                if (val != null) {
                    displayMessageBox(val, "Unable to Save", "Error");
                    return;
                }
                saveFontSettings();
                $(this).dialog("close");
            }
        }
    });

    $("#dimensionEditorDialog").dialog({
        resizable: false,
        height: 370,
        width: 276,
        modal: true,
        autoOpen: false,
        buttons: {
            "Save": function () {
                //                var val = validateDimensionFields();
                //                if (val != null) {
                //                    displayMessageBox("Unable to save as there are some fields that contain invalid data:<br/>" + val, "Unable to Save", "Error");
                //                    return;
                //                }
                saveDimensionSettings();
                $(this).dialog("close");
            }
        }
    });

    $("#btnFontEditor").click(function () {
        if (selectedObjectId == null)
            return;

        reflectOnFontEditor(selectedObjectId);
        $("#fontEditorDialog").dialog("open");
    });

    $("#btnDimensionEditor").click(function () {
        if (selectedObjectId == null)
            return;

        reflectOnDimensionEditor(selectedObjectId);
        $("#dimensionEditorDialog").dialog("open");
    });

    $("#txtColor").ColorPicker({
        onSubmit: function (hsb, hex, rgb, el) {
            $(el).val("#" + hex);
            $(el).ColorPickerHide();
            txtColor_Changed(null);
        },
        onBeforeShow: function () {
            $(this).ColorPickerSetColor($(this).val());
        }
    });

    $("#chkAutoplay").change(chkAutoplay_Changed);
    $("#txtAltText").keyup(function (event) {
        if (event.which == 13) {
            event.preventDefault();
            txtAltText_Changed(event);
        }
    });
    $("#txtColor").keyup(function (event) {
        if (event.which == 13) {
            event.preventDefault();
            $(this).ColorPickerSetColor($(this).val());
            txtColor_Changed(event);
        }
    });
    $("#txtAltText").change(txtColor_Changed);
    $("#txtColor").change(txtColor_Changed);

    $("#btnSource").click(btnSourceClicked);
    $("#btnUpload").click(function () {
        startUploadMedia();
    });
    $("#uploadResults").load(onUploadCompleted);

    $("#btnCommit").click(function () {
        startUploadMedia();
    });

    hideObjectProp();
});

var canvasId = -1;

function commitCanvas() {
    if (!isMediaUploaded)
        return;

    var objects = new Object();
    objects.textObjects = textObjects;
    objects.audioObjects = audioObjects;
    objects.videoObjects = videoObjects;
    objects.imageObjects = imageObjects;

    var serialized = $.toJSON(objects);
    var toSend = "<div id='commitCanvasContainer' style='visibility: hidden'>" +
                 "<iframe id='canvasCommitResults' name='canvasCommitResults' style='visibility: hidden'></iframe>" +
                 "<form id='canvasCommitter' action='../Learning/Controller/ContentManagementService.asmx/commitCanvas' method='POST' target='canvasCommitResults'>" +
                 "<input type='hidden' id='canvasId' name='canvasId' value='" + canvasId + "'/>" + 
                 "<textarea id='serializedObjects' name='serializedObjects'>" + serialized + "</textarea></form></div>";

    $("body").append(toSend);
    $("#canvasCommitResults").load(onCommittedCanvas);
    $("#canvasCommitter").trigger("submit");
    // invoke progress
}

function onCommittedCanvas(event) {
    var results = $("#canvasCommitResults").contents().find("string").text();
    $("#commitCanvasContainer").remove();
    if (results == "Done" || results == "done" || results == "DONE") {
        // stop progress
        displayMessageBox("Canvas Committed into the System Database. Press okay to return to Content Management.", "Commit Complete", "Information");
        window.location.replace("ContentEditorPOC1.htm");

        return;
    }

    displayMessageBox("Unable to commit canvas. Either there is error with the content or the system. Please try again later.", "Not Committed", "Alert");
}

function validateDimensionFields() {
    var fields = ["#txtHeight", "#txtWidth", "#txtLocX", "#txtLocY"];
    var errorMsg = "<ul>";
    var hasErrors = false;

    for (var i in fields) {
        var val = $(fields[i]).val();
        if (val == null || val == "") {
            hasErrors = true;
            errorMsg += "<li>" + fields[i].substring(4) + " is required.</li>";
            continue;
        }
        if (val < $(fields[i]).attr("min")) {
            hasErrors = true;
            errorMsg += "<li>" + fields[i].substring(4) + " is not within allowed range.</li>";
        }
    }

    return hasErrors ? errorMsg + "</ul>" : null;
}

function validateFontFields() {
    var val = $("#txtFontSize").val();

    if (val == null || val == "")
        return "The font size is a required field. Please enter a font size.";

    if (val < $("#txtFontSize").attr("min"))
        return "The font size is invalid. Valid size range from 1 to an arbitrarily large number";

    return null;
}

function ensurePosition(canvasDim, objDim, original, latest) {
    return latest >= 11 && latest + objDim <= canvasDim ? 1 : 0;
}

function ensureDimension(canvasDim, objPos, original, latest) {
    return latest >= 50 && latest <= getMaxDimension(canvasDim, objPos) ? 1 : 0;
}

function getMaxDimension(canvasDim, objPos) {
    return canvasDim - objPos;
}

function validateMedia(mediaArray) {
    var arrayToSearch = null;

    if (mediaArray == null)
        return true;

    for (var i in mediaArray) {
        arrayToSearch = mediaArray[i];
        if (arrayToSearch == null || arrayToSearch.length == 0)
            continue;

        for (var j in arrayToSearch) {
            var obj = arrayToSearch[j];
            if (obj.source == null || obj.source == "") {
                displayMessageBox("You cannot upload a canvas with media objects that do not have source. Check " + obj.id + ".", "Missing Media Source", "Error");
                return false;
            }
        }
    }

    return true;
}

function displayMessageBox(text, title, type) {
    var iconClass = "ui-icon ";

    if (type == "Information")
        iconClass += "ui-icon-info";
    else
        iconClass += "ui-icon-alert";

    $("body").append("<div id='messageBox' title='" + title + "'><p style='font-size: 12px;'><span class='" + iconClass + "' style='float:left; margin:0 7px 20px 0;'></span>" + text + "</p></div>");
    $("#messageBox").dialog({
        resizable: true,
        height: 150,
        autoOpen: true,
        modal: true,
        buttons: {
            "Okay": function () {
                $(this).dialog("close");
                $("#messageBox").remove();
            }
        }
    });
}

var uploadProcessInfo;
var isMediaUploaded = false;

function startUploadMedia() {
    var media = [audioObjects, imageObjects, videoObjects];

    if (uploadProcessInfo == null) {
        if (!validateMedia(media))
            return;

        uploadProcessInfo = new Object();
        uploadProcessInfo.media = media;
        uploadProcessInfo.currentMedia = 0;
        uploadProcessInfo.currentFile = 0;
        uploadProcessInfo.isUploading = false;
        // invoke show the progress
    }

    if (uploadProcessInfo.currentMedia < media.length &&
                uploadProcessInfo.currentFile < media[uploadProcessInfo.currentMedia].length) {

        var array = media[uploadProcessInfo.currentMedia];
        uploadProcessInfo.isUploading = true;
        uploadProcessInfo.objId = array[uploadProcessInfo.currentFile].id;
        enqueueUpload(uploadProcessInfo.objId);
        $("#fldMediaType").val(getObjectInArray(uploadProcessInfo.objId).type);
        $("#uploader").trigger("submit");

        return;
    }
    else if (uploadProcessInfo.currentMedia < media.length &&
                uploadProcessInfo.currentFile >= media[uploadProcessInfo.currentMedia].length) {
        uploadProcessInfo.currentMedia++;
        uploadProcessInfo.currentFile = 0;
        startUploadMedia();

        return;
    }

    if (uploadProcessInfo.currentMedia >= media.length) {
        uploadProcessInfo = null;
        $("#uploadResults").html("");
        if (media[0].length != 0 || media[1].length != 0 || media[2].length != 0)
            alert("Upload complete");
        isMediaUploaded = true;
        commitCanvas();
        // end the progress
    }
}

function enqueueUpload(id) {
    $("#uploader").append("<div id='queue-" + id + "'></div>");
    $("#queue-" + id).append($("#uploader-" + id));
}

function dequeueUpload(id) {
    $("#upload-" + id).append($("#uploader-" + id));
    $("#queue-" + id).remove();
}

function onUploadCompleted(event) {
    if (uploadProcessInfo == null || !uploadProcessInfo.isUploading)
        return;

    var result = $("#uploadResults").contents().find("string").text();
    var tokens = result.split(";");
    if (tokens[0] == "success") {
        var obj = getObjectInArray(uploadProcessInfo.objId);
        dequeueUpload(obj.id);
        obj.source = tokens[1];
        uploadProcessInfo.isUploading = false;
        uploadProcessInfo.currentFile++;
        if (uploadProcessInfo.currentFile >= uploadProcessInfo.media[uploadProcessInfo.currentMedia].length) {
            uploadProcessInfo.currentFile = 0;
            uploadProcessInfo.currentMedia++;
        }
    }

    $("#uploadResults").contents().empty();
    startUploadMedia();
}

function btnSourceClicked(event) {
    if (selectedObjectId == null || getObjectInArray(selectedObjectId).type == "TextBlock")
        return;

    var obj = getObjectInArray(selectedObjectId);
    $("#uploader-" + obj.id).trigger("click");

}

function txtSourceChanged(event) {
    if (selectedObjectId == null || getObjectInArray(selectedObjectId).type == "TextBlock")
        return;

    saveSourceSettings(selectedObjectId, this);
}

function saveSourceSettings(id, p) {
    var obj = getObjectInArray(id);
    var filepath = $("#uploader-" + id).val()
    var tokens = filepath.split(filepath.indexOf("\\") == -1 ? "/" : "\\");

    $("#txtSource").val(tokens[tokens.length - 1]);
    obj.source = $("#txtSource").val();

    if (obj.type == "ImageObject") {
        if (p.files.length) {
            var src = (window.URL) ? window.URL.createObjectURL(p.files[0]) : window.webkitURL.createObjectURL(p.files[0]);
            $("#" + id + " img").attr("src", src);
        }
    }
}

function chkAutoplay_Changed(event) {
    if (selectedObjectId == null || getObjectInArray(selectedObjectId).type == "ImageObject" ||
                    getObjectInArray(selectedObjectId).type == "TextBlock")
        return;

    saveMediaSettings(selectedObjectId);
}

function txtAltText_Changed(event) {
    if (selectedObjectId == null || getObjectInArray(selectedObjectId).type != "ImageObject")
        return;

    saveMediaSettings(selectedObjectId);
}

function txtColor_Changed(event) {
    if (selectedObjectId == null || getObjectInArray(selectedObjectId).type != "TextBlock")
        return;

    saveColorSettings(selectedObjectId);
}

function hideObjectProp() {
    var rowArray = ["#idRow", "#typeRow", "#sourceRow", "#altTextRow", "#autoplayRow", "#fontRow", "#colorRow", "#dimensionRow"];
    for (var i in rowArray)
        $(rowArray[i]).hide();
    $("#notSelectedRow").show();
}

function displayObjectProp(id) {
    var obj = getObjectInArray(id);

    $("#lblId").text(obj.id);
    $("#lblObjType").text(obj.type);

    $("#notSelectedRow").hide();
    $("#idRow").show();
    $("#typeRow").show();
    $("#dimensionRow").show();

    if (obj.type == "TextBlock") {
        $("#sourceRow").hide();
        $("#altTextRow").hide();
        $("#autoplayRow").hide();
        $("#fontRow").show();
        $("#colorRow").show();
    }
    else if (obj.type == "AudioObject") {
        $("#sourceRow").show();
        $("#altTextRow").hide();
        $("#autoplayRow").show();
        $("#fontRow").hide();
        $("#colorRow").hide();
    }
    else if (obj.type == "VideoObject") {
        $("#sourceRow").show();
        $("#altTextRow").hide();
        $("#autoplayRow").show();
        $("#fontRow").hide();
        $("#colorRow").hide();
    }
    else if (obj.type == "ImageObject") {
        $("#sourceRow").show();
        $("#altTextRow").show();
        $("#autoplayRow").hide();
        $("#fontRow").hide();
        $("#colorRow").hide();
    }

    reflectMediaSettings(obj.id, obj);
    reflectColorSettings(obj.id, obj);
}

function reflectMediaSettings(id, obj) {
    if (obj == null)
        obj = getObjectInArray(id);

    if (obj.type == "TextBlock")
        return;

    if (obj.type == "VideoObject" || obj.type == "AudioObject")
        $("#chkAutoplay").prop("checked", obj.autoplay);
    else
        $("#txtAltText").val(obj.altText);

    $("#txtSource").val(obj.source);
}

function reflectColorSettings(id, obj) {
    if (obj == null)
        obj = getObjectInArray(id);

    if (obj.type != "TextBlock")
        return;

    $("#txtColor").val(obj.color);
}

function saveMediaSettings(id) {
    var obj = getObjectInArray(id);

    if (obj == null || obj.type == "TextBlock")
        return;

    if (obj.type == "AudioObject" || obj.type == "VideoObject")
        obj.autoplay = $("#chkAutoplay").attr("checked") == "checked" ? true : false;
    else if (obj.type == "ImageObject")
        obj.altText = $("#txtAltText").val();

    updateObjectOnCanvas(obj);
}

function saveColorSettings(id) {
    var obj = getObjectInArray(id);

    if (obj == null || obj.type != "TextBlock")
        return;

    obj.color = $("#txtColor").val();
    updateObjectOnCanvas(obj);
}

function reflectOnFontEditor(id) {
    var obj = null;
    for (var i in textObjects) {
        if (textObjects[i].id == id) {
            obj = textObjects[i];
            break;
        }
    }

    var selectedFontName = $("#cmbFontName option:selected").val();
    if (selectedFontName.toLowerCase() != obj.fontName.toLowerCase()) {
        $("#cmbFontName option[value='" + selectedFontName + "']").removeAttr("selected");
        $("#cmbFontName option[value='" + obj.fontName + "']").attr("selected", "selected");
    }

    $("#txtFontSize").val(obj.fontSize);

    var selectedFontWeight = $("#cmbFontWeight option:selected").val();
    if (selectedFontWeight.toLowerCase() != obj.fontWeight.toLowerCase()) {
        $("#cmbFontWeight option[value='" + selectedFontWeight + "']").removeAttr("selected");
        $("#cmbFontWeight option[value='" + obj.fontWeight + "']").attr("selected", "selected");
    }

    var selectedTextDeco = $("#cmbTextDecoration option:selected").val();
    if (selectedTextDeco.toLowerCase() != obj.textDecoration.toLowerCase()) {
        $("#cmbTextDecoration option[value='" + selectedTextDeco + "']").removeAttr("selected");
        $("#cmbTextDecoration option[value='" + obj.textDecoration + "']").attr("selected", "selected");
    }

    var selectedFontStyle = $("#cmbFontStyle option:selected").val();
    if (selectedFontStyle.toLowerCase() != obj.fontStyle.toLowerCase()) {
        $("#cmbFontStyle option[value='" + selectedFontStyle + "']").removeAttr("selected");
        $("#cmbFontStyle option[value='" + obj.fontStyle + "']").attr("selected", "selected");
    }
}

function reflectOnDimensionEditor(id) {
    var obj = null;

    var objectType = $("#" + id).attr("objectType");
    var arrayToSearch = null;
    if (objectType == "TextBlock")
        arrayToSearch = textObjects;
    else if (objectType == "AudioObject")
        arrayToSearch = audioObjects;
    else if (objectType == "VideoObject")
        arrayToSearch = videoObjects;
    else if (objectType == "ImageObject")
        arrayToSearch = imageObjects;

    for (var i in arrayToSearch) {
        if (arrayToSearch[i].id == id) {
            obj = arrayToSearch[i];
            break;
        }
    }

    if (objectType == "AudioObject" || objectType == "VideoObject") {
        $("#lblHeight").prop("disabled", true);
        $("#txtHeight").prop("disabled", true);
        $("#lblWidth").prop("disabled", true);
        $("#txtWidth").prop("disabled", true);
    }
    else {
        $("#lblHeight").prop("disabled", false);
        $("#txtHeight").prop("disabled", false);
        $("#lblWidth").prop("disabled", false);
        $("#txtWidth").prop("disabled", false);
        $("#txtHeight").val(obj.height);
        $("#txtWidth").val(obj.width);
    }

    $("#txtLocX").val(obj.x);
    $("#txtLocY").val(obj.y);
}

function saveFontSettings() {
    if (selectedObjectId == null)
        return;

    var objectType = $("#" + selectedObjectId).attr("objectType");
    if (objectType != "TextBlock")
        return;

    for (var i in textObjects) {
        var x = textObjects[i];
        if (x.id == selectedObjectId) {
            x.fontName = $("#cmbFontName").val();
            x.fontSize = $("#txtFontSize").val();
            x.fontWeight = $("#cmbFontWeight").val();
            x.textDecoration = $("#cmbTextDecoration").val();
            x.fontStyle = $("#cmbFontStyle").val();
            updateObjectOnCanvas(x);

            break;
        }
    }
}

function saveDimensionSettings() {
    if (selectedObjectId == null)
        return;

    var objectType = $("#" + selectedObjectId).attr("ObjectType");

    var x = getObjectInArray(selectedObjectId);
    var height = $("#txtHeight").val();
    var width = $("#txtWidth").val();
    var locX = $("#txtLocX").val();
    var locY = $("#txtLocY").val();
    var canvasH = $("#EditingCanvas").height();
    var canvasW = $("#EditingCanvas").width();

    if (locX == null || locY == null)
        return;

    var valY = ensurePosition(canvasH, x.height, x.y, locY);
    var valX = ensurePosition(canvasW, x.width, x.x, locX);

    x.x = (valX == 0 ? x.x : locX);
    x.y = (valY == 0 ? x.y : locY);

    if (objectType == "TextBlock" || objectType == "ImageObject") {
        if (height == null || width == null)
            return;

        var valh = ensureDimension(canvasH, locY, x.height, height);
        var valw = ensureDimension(canvasW, locX, x.width, width);

        x.height = valh == 0 ? x.height : height;
        x.width = valw == 0 ? x.width : width;
    }

    updateObjectOnCanvas(x);
}

function updateObjectOnCanvas(obj) {
    if (obj.type == "TextBlock") {
        $("#" + obj.id + " textarea").css("font-family", obj.fontName);
        $("#" + obj.id + " textarea").css("font-size", obj.fontSize + "px");
        $("#" + obj.id + " textarea").css("font-weight", obj.fontWeight);
        $("#" + obj.id + " textarea").css("text-decoration", obj.textDecoration);
        $("#" + obj.id + " textarea").css("font-style", obj.fontStyle);
        $("#" + obj.id + " textarea").css("color", obj.color);
        $("#" + obj.id).height(obj.height);
        $("#" + obj.id).width(obj.width);
    }
    else if (obj.type == "AudioObject") {
        $("#" + obj.id + " audio").attr("src", obj.source);
        if (obj.autoplay)
            $("#" + obj.id + " audio").attr("autoplay", "autoplay");
    }
    else if (obj.type == "VideoObject") {
        $("#" + obj.id + " video").attr("src", obj.source);
        if (obj.autoplay)
            $("#" + obj.id + " video").attr("autoplay", "autoplay");
    }
    else if (obj.type == "ImageObject") {
        $("#" + obj.id + " img").attr("src", obj.source);
        $("#" + obj.id + " img").attr("alt", obj.altText);
        $("#" + obj.id).height(obj.height);
        $("#" + obj.id).width(obj.width);
    }

    $("#" + obj.id).css("left", obj.x + "px");
    $("#" + obj.id).css("top", obj.y + "px");
}

function parseKeyPressed(event) {
    if (event.which == 46 && selectedObjectId != null && !textAreaFocused) {
        event.preventDefault();
        $("#confirmDeleteDialog").dialog("open");
    }
    else if (event.which == 27 && selectedObjectId != null) {
        event.preventDefault();
        selectedObjectId = null;
        hideObjectProp();
    }
}

function removeCanvasItem() {
    var type = $("#" + selectedObjectId).attr("objectType");
    var arrayLength = 0;
    var theObjects = null;

    if (type == "TextBlock") {
        theObjects = textObjects;
        arrayLength = textObjects.length;
    }
    else if (type == "AudioObject") {
        theObjects = audioObjects;
        arrayLength = audioObjects.length;
    }
    else if (type == "VideoObject") {
        theObjects = videoObjects;
        arrayLength = videoObjects.length;
    }
    else if (type == "ImageObject") {
        theObjects = imageObjects;
        arrayLength = imageObjects.length;
    }

    for (var i = 0; i < arrayLength; ++i) {
        if (theObjects[i].id == selectedObjectId) {
            theObjects.splice(i, 1);
            break;
        }
    }

    $("#" + selectedObjectId).remove();
    selectedObjectId = null;
    hideObjectProp();
}

function onTextBlockChanged(event){
    if (selectedObjectId == null || getObjectInArray(selectedObjectId).type != "TextBlock")
        return;
    saveTextBlockText(selectedObjectId);
}

function saveTextBlockText(id) {
    var obj = getObjectInArray(id);
    obj.text = $("#" + id + " textarea").val();
}

function addNewCanvasItem(event, ui) {
    var id = ui.draggable.attr("id");
    var objName = null;

    if (id == "objText") {
        objName = "TextObject" + (++numOfTextObj);
        $(this).append("<div id='" + objName + "' class='ui-widget-content ui-corner-all CanvasObjectContainer' objectType='TextBlock'><textarea class='CanvasTextObject'>Enter text here</textarea></div>");
        $("#" + objName).resizable({ containment: '#EditingCanvas', stop: canvasItemResizeStopped });
        $("#" + objName).draggable({ containment: '#EditingCanvas', stop: canvasItemDragStopped });
        $("#" + objName + " textarea").focus(function (event) {
            textAreaFocused = true;
        });
        $("#" + objName + " textarea").blur(function (event) {
            textAreaFocused = false;
        });
        $("#" + objName + " textarea").change(onTextBlockChanged);

        var objText = new Object();
        objText.id = objName;
        objText.type = "TextBlock";
        objText.text = "Enter text here";
        objText.fontName = "Georgia";
        objText.fontSize = 11;
        objText.fontWeight = "normal";
        objText.textDecoration = "none";
        objText.fontStyle = "normal";
        objText.color = "#000000";
        objText.x = (ui.position.left + $("#" + objName).width() < ($(this).width() - 20)) ? ui.position.left : ($(this).width() - 20) - $("#" + objName).width();
        objText.y = (ui.position.top + $("#" + objName).height() < ($(this).height() - 20)) ? ui.position.top : ($(this).height() - 20) - $("#" + objName).height();
        objText.height = $("#" + objName).height();
        objText.width = $("#" + objName).width();
        textObjects.push(objText);
    }
    else if (id == "objAudio") {
        objName = "AudioObject" + (++numOfAudioObj);
        $(this).append("<div id='" + objName + "' class='CanvasAudioObject' objectType='AudioObject'><audio src='res/audio1.mp3' controls='controls'/></div>");
        $("#" + objName).draggable({ containment: '#EditingCanvas', stop: canvasItemDragStopped });
        $("#uploads").append("<div id='upload-" + objName + "'><input type='file' id='uploader-" + objName + "' name='mediaToUpload' accept='audio/mp3'/></div>");
        $("#uploader-" + objName).change(txtSourceChanged);

        var objAudio = new Object();
        objAudio.id = objName;
        objAudio.type = "AudioObject";
        objAudio.source = "";
        objAudio.autoplay = false;
        objAudio.x = (ui.position.left + $("#" + objName).width() < ($(this).width() - 20)) ? ui.position.left : ($(this).width() - 20) - $("#" + objName).width();
        objAudio.y = (ui.position.top + $("#" + objName).height() < ($(this).height() - 20)) ? ui.position.top : ($(this).height() - 20) - $("#" + objName).height();
        audioObjects.push(objAudio);
    }
    else if (id == "objVideo") {
        objName = "VideoObject" + (++numOfVideoObj);
        $(this).append("<div id='" + objName + "' class='CanvasVideoObject' objectType='VideoObject'><video src='res/video1.mp4' height='270px' width='480px' controls='controls'/></div>");
        $("#" + objName).draggable({ containment: '#EditingCanvas', stop: canvasItemDragStopped });
        $("#uploads").append("<div id='upload-" + objName + "'><input type='file' id='uploader-" + objName + "' name='mediaToUpload' accept='video/mp4'/></div>");
        $("#uploader-" + objName).change(txtSourceChanged);

        var objVideo = new Object();
        objVideo.id = objName;
        objVideo.type = "VideoObject";
        objVideo.source = "";
        objVideo.autoplay = false;
        objVideo.x = (ui.position.left + $("#" + objName).width() < ($(this).width() - 20)) ? ui.position.left : ($(this).width() - 20) - $("#" + objName).width();
        objVideo.y = (ui.position.top + $("#" + objName).height() < ($(this).height() - 20)) ? ui.position.top : ($(this).height() - 20) - $("#" + objName).height();
        videoObjects.push(objVideo);
    }
    else if (id == "objImage") {
        objName = "ImageObject" + (++numOfImageObj);
        $(this).append("<div id='" + objName + "' class='ui-widget-content ui-corner-all CanvasImageFrame' objectType='ImageObject'><img class='CanvasImageObject' src='res/image.png' alt='ImageObject'/></div>");
        $("#" + objName).draggable({ containment: '#EditingCanvas', stop: canvasItemDragStopped }).resizable({ containment: "#EditingCanvas", stop: canvasItemResizeStopped });
        $("#uploads").append("<div id='upload-" + objName + "'><input type='file' id='uploader-" + objName + "' name='mediaToUpload' accept='image/*'/></div>");
        $("#uploader-" + objName).change(txtSourceChanged);

        var objImage = new Object();
        objImage.id = objName;
        objImage.type = "ImageObject";
        objImage.source = "";
        objImage.altText = "Image Object";
        objImage.height = $("#" + objName).height();
        objImage.width = $("#" + objName).width();
        objImage.x = (ui.position.left + $("#" + objName).width() < ($(this).width() - 20)) ? ui.position.left : ($(this).width() - 20) - $("#" + objName).width();
        objImage.y = (ui.position.top + $("#" + objName).height() < ($(this).height() - 20)) ? ui.position.top : ($(this).height() - 20) - $("#" + objName).height();
        imageObjects.push(objImage);
    }

    $("#" + objName).click(canvasItemClicked);
    $("#" + objName).css("position", "absolute");
    $("#" + objName).css('top', (ui.position.top + $("#" + objName).height() < ($(this).height() - 20)) ? ui.position.top : ($(this).height() - 20) - $("#" + objName).height());
    $("#" + objName).css('left', (ui.position.left + $("#" + objName).width() < ($(this).width() - 20)) ? ui.position.left : ($(this).width() - 20) - $("#" + objName).width());
}

function canvasItemDragStopped(event, ui) {
    updateAfterDragged($(event.target).attr("id"));
    $(event.target).trigger("click");
}

function canvasItemResizeStopped(event, ui) {
    updateAfterResized($(event.target).attr("id"));
    $(event.target).trigger("click");
}

function getObjectInArray(id) {
    var toReturn;
    var objType = $("#" + id).attr("objectType");
    var arrayToSearch = null;

    if (objType == "TextBlock")
        arrayToSearch = textObjects;
    else if (objType == "AudioObject")
        arrayToSearch = audioObjects;
    else if (objType == "VideoObject")
        arrayToSearch = videoObjects;
    else if (objType == "ImageObject")
        arrayToSearch = imageObjects;


    for (var i in arrayToSearch) {
        if (arrayToSearch[i].id == id) {
            toReturn = arrayToSearch[i];
            break;
        }
    }

    return toReturn;
}

function updateAfterDragged(id) {
    var obj = getObjectInArray(id);

    if (obj == null)
        return;

    obj.x = $("#" + id).position().left;
    obj.y = $("#" + id).position().top;

}

function updateAfterResized(id) {
    var obj = getObjectInArray(id);

    if (obj == null)
        return;

    obj.height = $("#" + id).height();
    obj.width = $("#" + id).width();
}

function canvasItemClicked(event) {
    var id = $(event.currentTarget).attr("id");
    var isTextArea = $(event.target).is("textarea");
    selectCanvasItem(id, isTextArea);
}

function selectCanvasItem(id, isTextArea) {
    if (textAreaFocused && !isTextArea)
        $("#EditingCanvas textarea").trigger("blur");
    selectedObjectId = id;
    displayObjectProp(id);
}